package com.hlju.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hlju.reggie.bean.Dish;
import com.hlju.reggie.bean.Flavor;
import com.hlju.reggie.bean.dto.DishDto;
import com.hlju.reggie.mapper.DishMapper;
import com.hlju.reggie.service.DishService;
import com.hlju.reggie.service.FlavorService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private FlavorService flavorService;

    @Override
    @Transactional
    public void saveDish(DishDto dto) {
        //给菜品设置一个排序
        dto.setSort(1);
        //将菜品的基本信息保存到菜品表
        this.save(dto);

        //获取dto对象中的口味集合
        List<Flavor> flavors = dto.getFlavors();
        //遍历集合
        for (Flavor flavor : flavors) {
            //给口味对象设置所属菜品id
            flavor.setDishId(dto.getId());
        }
        //批量保存口味
        flavorService.saveBatch(flavors);
    }

    @Override
    public DishDto getDishWithFlavors(Long id) {
        //根据id查询菜品信息
        Dish dish = this.getById(id);
        //创建Dto对象
        DishDto dto = new DishDto();
        //将菜品对象的属性复制到dto中
        BeanUtils.copyProperties(dish,dto);
        //创建条件构造器
        QueryWrapper<Flavor> wrapper = new QueryWrapper<>();
        //将菜品id作为条件
        wrapper.eq("dish_id",id);
        //根据条件查询口味列表
        List<Flavor> flavorList = flavorService.list(wrapper);
        //将口味集合设置给dto对象
        dto.setFlavors(flavorList);
        //返回dto对象
        return dto;
    }

    @Override
    @Transactional
    public void updateDishWithFlavors(DishDto dto) {
        //修改菜品
        this.updateById(dto);
        //根据菜品id删除口味表相关数据
        QueryWrapper<Flavor> wrapper = new QueryWrapper<>();
        wrapper.eq("dish_id",dto.getId());
        flavorService.remove(wrapper);
        //获取传递过来的口味集合
        List<Flavor> flavorList = dto.getFlavors();
        //遍历口味集合
        for (Flavor flavor : flavorList) {
            //给口味设置所属的菜品id
            flavor.setDishId(dto.getId());
        }
        //批量保存口味
        flavorService.saveBatch(flavorList);
    }
}
